package com.api.shop.interceptor;

import com.api.shop.bean.SysUser;
import com.api.shop.common.NoLoginUrl;
import com.api.shop.common.RequestHolder;
import com.api.shop.exception.PermissionException;
import com.api.shop.util.ClassUtil;
import com.api.shop.util.MyStringUtil;
import com.api.shop.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class MyUrlInterceptor extends HandlerInterceptorAdapter {

//    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("this interceptor is MyUrlInterceptor");

        String method = request.getMethod();
        if(method.equals("OPTIONS")){
            return true;
        }

        String url;
        String token;
        String userStr;
        SysUser user;

        url = validateNoPermissionUrl(request);
        if (url.equals("NoPermissionsRequired")){
            return true;
        }

        token = validateToken(request);

        userStr = validateLogin(token, request);

        String ip = request.getRemoteAddr();

        user = MyStringUtil.StringToObject(userStr);
        log.info("interceptor user: {}", user);
        RequestHolder.add(user);
        RequestHolder.add(token);
        log.info("RequestHolder: " + RequestHolder.getCurrentUser() + ", " + RequestHolder.getCurrentToken());

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        RequestHolder.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }

    private String validateNoPermissionUrl(HttpServletRequest request){
        String url = request.getRequestURI().trim();
        log.info("request url: {}", url);

        Map<String, Object> map = NoLoginUrl.getMap();
        if(map != null){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                log.info("map: key: {}, value:{}", entry.getKey(), entry.getValue());
                if(url.contains(String.valueOf(entry.getValue()))){
                    return "NoPermissionsRequired";
                }
            }
        }
        return url;
    }

    private String validateToken(HttpServletRequest request){
        String token = request.getHeader("token");
        log.info("interceptor token: {}", token);
        if(token == null || token.isEmpty()){
            throw new PermissionException("请将 token 放入请求头部进行 url 请求");
        }

        return token;
    }

    private String validateLogin(String token, HttpServletRequest request){
        redisUtil = ClassUtil.getClassT(RedisUtil.class, request);

        String userStr = (String)redisUtil.get(token);
        if(userStr == null){
            throw new PermissionException("请登录后进行操作");
        }
        String userId = userStr.substring(userStr.indexOf("=") + 1, userStr.indexOf(","));
        String redisToken = (String)redisUtil.get("userId_" + userId);
        log.info("token: {}", token);
        log.info("redisToken: {}", redisToken);
        log.info("userId: {}", userId);
        if(!redisToken.equals(token)){
            throw new PermissionException("您的账号在其他地方登录，请确认是否是本人操作");
        }
        if(userStr == null){
            throw new PermissionException("请登录后再进行操作");
        }

        return userStr;
    }

}
